<template>
  <div class="text-converter">
    <div class="header">
      <h1>🔤 文字转换工具</h1>
      <p>提供多种文本处理和转换功能</p>
    </div>

    <div class="converter-container">
      <!-- 功能标签页 -->
      <div class="tabs">
        <button 
          v-for="tab in tabs" 
          :key="tab.id"
          :class="['tab', { active: activeTab === tab.id }]"
          @click="activeTab = tab.id"
        >
          {{ tab.icon }} {{ tab.name }}
        </button>
      </div>

      <!-- 输入输出区域 -->
      <div class="io-section">
        <div class="input-section">
          <div class="input-header">
            <label>输入文本</label>
            <button @click="loadExample" class="example-btn" v-if="currentExample">
              📝 加载示例
            </button>
          </div>
          <textarea 
            v-model="inputText" 
            :placeholder="currentPlaceholder"
            rows="10"
          ></textarea>
          <div class="example-info" v-if="currentExample">
            <strong>示例说明：</strong>{{ currentExample.description }}
          </div>
        </div>
        
        <div class="output-section">
          <label>输出结果</label>
          <textarea 
            v-model="outputText" 
            placeholder="转换结果将显示在这里..."
            rows="10"
            readonly
          ></textarea>
        </div>
      </div>

      <!-- 功能按钮区域 -->
      <div class="functions-section">
        <h3>{{ getCurrentTabName() }} 功能</h3>
        <p class="function-tip" v-if="!inputText.trim()">💡 请先输入文本，然后点击功能按钮即可直接转换</p>
        <p class="function-tip" v-else>💡 点击下方功能按钮即可直接执行转换</p>
        <div class="function-buttons">
          <button 
            v-for="func in currentTabFunctions" 
            :key="func.id"
            :class="['function-btn', { processing: isProcessing, selected: selectedFunction === func.id }]"
            @click="selectFunction(func.id)"
            :disabled="isProcessing || !inputText.trim()"
          >
            <span v-if="isProcessing && selectedFunction === func.id">⏳ 转换中...</span>
            <span v-else>{{ func.name }}</span>
          </button>
        </div>
        
        <!-- 执行按钮已集成到功能按钮中，无需单独显示 -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { 
  processText,
  tabs,
  functions
} from '../composables/useTextConverter.js'

// 响应式数据
const activeTab = ref('case')
const inputText = ref('')
const outputText = ref('')
const isProcessing = ref(false)

// 每个功能的示例数据映射
const functionExamples = {
  // 大小写转换
  camelCase: { text: 'hello world', description: '将文本转换为驼峰命名格式' },
  pascalCase: { text: 'hello world', description: '将文本转换为帕斯卡命名格式' },
  snakeCase: { text: 'hello world', description: '将文本转换为下划线命名格式' },
  kebabCase: { text: 'hello world', description: '将文本转换为短横线命名格式' },
  constantCase: { text: 'hello world', description: '将文本转换为常量命名格式' },
  dotCase: { text: 'hello world', description: '将文本转换为点分命名格式' },
  pathCase: { text: 'hello world', description: '将文本转换为路径命名格式' },
  sentenceCase: { text: 'hello world', description: '将文本转换为句子格式' },
  titleCase: { text: 'hello world', description: '将文本转换为标题格式' },
  upperCase: { text: 'hello world', description: '将文本转换为全大写' },
  lowerCase: { text: 'HELLO WORLD', description: '将文本转换为全小写' },
  
  // 转义/反转义
  escapeJava: { text: 'Hello "World"\nNew Line', description: 'Java字符串转义' },
  unescapeJava: { text: 'Hello \"World\"\\nNew Line', description: 'Java字符串反转义' },
  escapeJavaScript: { text: 'Hello "World"\nNew Line', description: 'JavaScript字符串转义' },
  unescapeJavaScript: { text: 'Hello \"World\"\\nNew Line', description: 'JavaScript字符串反转义' },
  escapeHtml: { text: '<div>Hello & "World"</div>', description: 'HTML字符转义' },
  unescapeHtml: { text: '&lt;div&gt;Hello &amp; &quot;World&quot;&lt;/div&gt;', description: 'HTML字符反转义' },
  escapeJson: { text: '{"name": "张三", "message": "Hello\nWorld"}', description: 'JSON字符串转义' },
  unescapeJson: { text: '{\"name\": \"张三\", \"message\": \"Hello\\nWorld\"}', description: 'JSON字符串反转义' },
  escapeXml: { text: '<root>Hello & "World"</root>', description: 'XML字符转义' },
  unescapeXml: { text: '&lt;root&gt;Hello &amp; &quot;World&quot;&lt;/root&gt;', description: 'XML字符反转义' },
  escapeUnicode: { text: '你好世界', description: 'Unicode字符转义' },
  unescapeUnicode: { text: '\\u4f60\\u597d\\u4e16\\u754c', description: 'Unicode字符反转义' },
  
  // 编码/解码
  md5: { text: 'Hello World', description: '计算MD5哈希值' },
  sha1: { text: 'Hello World', description: '计算SHA-1哈希值' },
  sha256: { text: 'Hello World', description: '计算SHA-256哈希值' },
  sha512: { text: 'Hello World', description: '计算SHA-512哈希值' },
  base64Encode: { text: 'Hello World 你好', description: 'Base64编码' },
  base64Decode: { text: 'SGVsbG8gV29ybGQg5L2g5aW9', description: 'Base64解码' },
  urlEncode: { text: 'https://example.com/search?q=你好世界', description: 'URL编码' },
  urlDecode: { text: 'https%3A//example.com/search%3Fq%3D%E4%BD%A0%E5%A5%BD%E4%B8%96%E7%95%8C', description: 'URL解码' },
  hexEncode: { text: 'Hello 你好', description: '十六进制编码' },
  hexDecode: { text: '48656c6c6f20e4bda0e5a5bd', description: '十六进制解码' },
  
  // 数字处理
  incrementNumbers: { text: 'Item 1\nItem 2\nItem 3', description: '递增文本中的数字' },
  decrementNumbers: { text: 'Item 5\nItem 4\nItem 3', description: '递减文本中的数字' },
  createSequence: { text: '5', description: '创建数字序列（输入数字表示序列长度）' },
  
  // 排序
  sortAscending: { text: 'zebra\napple\nbanana\ncat', description: '按字母升序排列' },
  sortDescending: { text: 'apple\nbanana\ncat\nzebra', description: '按字母降序排列' },
  sortByLength: { text: 'a\nlong text\nmedium\nshort', description: '按长度排序' },
  shuffle: { text: 'apple\nbanana\ncherry\ndate', description: '随机打乱顺序' },
  reverse: { text: 'first\nsecond\nthird\nlast', description: '反转行顺序' },
  sortJson: { text: '{"c": 3, "a": 1, "b": 2}', description: '对JSON对象的键进行排序' },
  
  // 对齐
  alignLeft: { text: '  左边有空格\n中间文本\n    右边也有空格  ', description: '左对齐文本' },
  alignCenter: { text: 'short\nmedium text\nlong text content', description: '居中对齐文本' },
  alignRight: { text: 'short\nmedium text\nlong text content', description: '右对齐文本' },
  
  // 过滤/清理
  removeDuplicates: { text: 'apple\nbanana\napple\ncherry\nbanana', description: '去除重复行' },
  removeEmptyLines: { text: 'line 1\n\nline 2\n\n\nline 3', description: '移除空行' },
  trimLines: { text: '  spaces before\nspaces after  \n  both sides  ', description: '修剪每行的空格' },
  removeAllSpaces: { text: 'hello world\nremove spaces', description: '移除所有空格' },
  compressSpaces: { text: 'multiple    spaces   here', description: '压缩多个空格为单个空格' },
  
  // 其他操作
  reverseText: { text: 'Hello World', description: '反转文本字符顺序' },
  swapQuotes: { text: 'He said "Hello\'s world"', description: '交换单引号和双引号' },
  removeLineBreaks: { text: 'line 1\nline 2\nline 3', description: '移除换行符' }
}

// 当前选中的功能
const selectedFunction = ref('')

// 默认标签页示例数据
const defaultTabExamples = {
  case: { text: 'hello world\nuser_name\ngetUserInfo', description: '演示各种命名格式转换' },
  escape: { text: 'Hello "World"\nLine 1\nLine 2', description: '演示转义和反转义功能' },
  encode: { text: 'Hello World 你好世界', description: '演示编码解码功能' },
  number: { text: 'Item 1\nItem 2\nItem 3', description: '演示数字处理功能' },
  sort: { text: 'zebra\napple\nbanana\ncat', description: '演示排序功能' },
  align: { text: '  左边有空格\n中间文本\n    右边也有空格', description: '演示对齐功能' },
  filter: { text: 'apple\nbanana\napple\n\ncherry', description: '演示过滤清理功能' },
  other: { text: 'Hello World\nReverse this text', description: '演示其他文本操作' }
}

// 计算属性
const currentExample = computed(() => {
  if (selectedFunction.value) {
    return functionExamples[selectedFunction.value] || null
  }
  return defaultTabExamples[activeTab.value] || null
})

const currentPlaceholder = computed(() => {
  const tab = tabs.find(t => t.id === activeTab.value)
  return tab ? tab.placeholder : '请输入要转换的文本...'
})

const currentTabFunctions = computed(() => {
  return functions.filter(func => func.category === activeTab.value)
})

// 方法
const getCurrentTabName = () => {
  const tab = tabs.find(t => t.id === activeTab.value)
  return tab ? tab.name : ''
}

const loadExample = () => {
  if (currentExample.value) {
    inputText.value = currentExample.value.text.replace(/\\n/g, '\n')
  }
}

const selectFunction = async (functionId) => {
  selectedFunction.value = functionId
  // 自动执行转换，实现一键操作
  if (inputText.value.trim()) {
    await executeFunction(functionId)
  }
}

// 监听标签页切换，重置选中的功能
watch(activeTab, () => {
  selectedFunction.value = ''
})

const executeFunction = async (functionId) => {
  if (!inputText.value.trim()) {
    alert('请先输入要转换的文本')
    return
  }
  
  isProcessing.value = true
  
  try {
    let result
    
    switch (activeTab.value) {
      case 'case':
      case 'escape':
      case 'encode':
      case 'number':
      case 'sort':
      case 'align':
      case 'filter':
      case 'other':
        result = processText(inputText.value, functionId)
        break
      default:
        result = '未知的转换类型'
    }
    
    outputText.value = result
  } catch (error) {
    console.error('转换失败:', error)
    outputText.value = '转换失败: ' + error.message
  } finally {
    isProcessing.value = false
  }
}
</script>

<style scoped>
.text-converter {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h1 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.header p {
  color: #7f8c8d;
  font-size: 16px;
}

.converter-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.tabs {
  display: flex;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  overflow-x: auto;
}

.tab {
  flex: 1;
  min-width: 120px;
  padding: 15px 10px;
  border: none;
  background: transparent;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  white-space: nowrap;
}

.tab:hover {
  background: #e9ecef;
}

.tab.active {
  background: #007bff;
  color: white;
}

.io-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  padding: 20px;
}

@media (max-width: 768px) {
  .io-section {
    grid-template-columns: 1fr;
  }
}

.input-section,
.output-section {
  display: flex;
  flex-direction: column;
}

.input-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

label {
  font-weight: 600;
  color: #495057;
  margin-bottom: 8px;
}

textarea {
  width: 100%;
  padding: 12px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 14px;
  line-height: 1.5;
  resize: vertical;
  transition: border-color 0.3s ease;
}

textarea:focus {
  outline: none;
  border-color: #007bff;
}

textarea[readonly] {
  background-color: #f8f9fa;
}

.example-btn {
  padding: 6px 12px;
  background: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.3s ease;
}

.example-btn:hover {
  background: #218838;
}

.example-info {
  margin-top: 8px;
  padding: 8px;
  background: #e7f3ff;
  border-left: 4px solid #007bff;
  border-radius: 4px;
  font-size: 12px;
  color: #0277bd;
}

.functions-section {
  padding: 20px;
  border-top: 1px solid #e9ecef;
  background: #f8f9fa;
}

.functions-section h3 {
  margin: 0 0 15px 0;
  color: #495057;
}

.function-tip {
  margin: 0 0 15px 0;
  padding: 10px 15px;
  background: #e7f3ff;
  border-left: 4px solid #007bff;
  border-radius: 4px;
  font-size: 14px;
  color: #0277bd;
}

.function-buttons {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 10px;
}

.function-btn {
  padding: 10px 15px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  text-align: left;
}

.function-btn:hover:not(:disabled) {
  background: #0056b3;
  transform: translateY(-1px);
}

.function-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
  transform: none;
}

.function-btn.processing {
  background: #ffc107;
  color: #212529;
}

.function-btn.selected {
  background: #28a745;
  border: 2px solid #1e7e34;
}

.function-btn.selected:hover:not(:disabled) {
  background: #218838;
}

.execute-section {
  margin-top: 20px;
  text-align: center;
}

.execute-btn {
  padding: 12px 30px;
  background: #dc3545;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.execute-btn:hover:not(:disabled) {
  background: #c82333;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.execute-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}
</style>